package demo;

import java.util.Arrays;
import java.util.Objects;
import java.util.Random;

public class demo2 {

    private static final Random RANDOM = new Random();

    public static void main(String[] args) throws Exception {
        int[] arr = {1, 2, 6, 2, 4, 3, 1, 0};
        quickSort(arr);
        System.out.println(Arrays.toString(arr));

    }


    public static void quickSort(int[] arr) throws Exception {
        quickSortInternal(Objects.requireNonNull(arr), 0, arr.length - 1);
    }

    private static void quickSortInternal(int[] arr, int l, int r) {
        if (l > r) {
            return;
        }
        int p = partition(arr, l, r);
        // 以最后基准值的位置作为分割线，剩下的部分去递归
        quickSortInternal(arr, l,  p - 1);
        quickSortInternal(arr,  p + 1, r);
    }

    private static int partition(int[] arr, int l, int r) {
        swap(arr, l, RANDOM.nextInt(l, r + 1));
        int base = arr[l];
        int curIndex = l;
        for (int i = l + 1; i <= r; i++) {
            if (arr[i] < base) {
                swap(arr, curIndex++ + 1, i);
            }
        }
        swap(arr, l, curIndex);
        return curIndex;
    }

    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

}
